#include "MiniCloudHandler.h"

MiniCloudHandler::MiniCloudHandler(MiniObject *obj) : MiniHandler(obj)
{
    UpdateHandler();
}

float MiniCloudHandler::CheckCollision(QPointF pos, QMatrix4x4 projection)
{
    MiniCloud *cloud = (MiniCloud*)m_object;

    // 第一个数组存放顶点信息
    int n = cloud->GetPointsNum();
    MiniArray<Vector3f> &vertices = cloud->GetPoints();
    for (int i = 0; i < n; i++)
    {
        QVector4D v = projection * QVector4D{vertices[i].x(), vertices[i].y(), vertices[i].z(), 1};
        v = v / v.w();

        // 如果拾取到，返回 z 坐标判断深度
        if ((QPointF{v.x(), v.y()} - pos).manhattanLength() < 0.01)
        {
            m_vertex = &vertices.at(i);
            return v.z();
        }
    }
    return 1;
}

void MiniCloudHandler::ChangeVertex(Vector3f dv)
{
    Q_UNUSED(dv)
}

void MiniCloudHandler::UpdateHandler()
{
    InitHandler();

    // 转化为 cloud 指针操作
    MiniCloud *cloud = (MiniCloud*)m_object;

    const MiniArray<Vector3f> &points = cloud->GetPoints();
    int n = points.size();
    float* vertices = new float[n * 3];
    unsigned int* indices = new unsigned int[n];
    for (int i = 0; i < n; i++)
    {
        indices[i] = i;
        vertices[i * 3 + 0] = points[i].x();
        vertices[i * 3 + 1] = points[i].y();
        vertices[i * 3 + 2] = points[i].z();
    }

    // 储存数据
    m_countIndices.push_back(n);
    m_countVertices.push_back(n);
    m_vertices.push_back(vertices);
    m_indices.push_back(indices);
    m_modes.push_back(GL_POINTS);
    m_color.push_back(m_basisColor);
}
